import Taro, { useDidShow } from '@tarojs/taro';
import React from 'react';
import LoginH5 from './components/h5Wrap';
import WechatWrap from './components/wechatWrap';
import currentEnv from '../../../../configure/currentEnv';
import {handleMiniprogram} from '@/utils/Tools'
import wx from '@/utils/weixin-js-sdk/index'
import { View } from '@tarojs/components';

function checkIsNeedBack() {
  if(process.env.TARO_ENV == 'h5' && process.env.NODE_ENV == 'production'){
    if(handleMiniprogram()){
      wx.miniProgram.redirectTo({
        url: '/pages/login/wxLogin/wxLogin'
      })
    }else{
      location.href=`fineengine://pages/login/wxLogin/wxLogin`
    }
    return;
  }
  let user = Taro.getStorageSync('user');
  const {timestamp} = user

  // 登录记录 大于10秒, 说明是历史登录, 不需要返回
  if (Date.now() - timestamp > 10 * 1000) {
    return false;
  }

  // 有 accessToken 需要返回
  if (user?.token?.accessToken && Taro.getStorageSync('userSource') === 'USER') {
    console.log('已经登录成功, 返回上一级');

    Taro.navigateBack().catch((e) => {
      console.warn('返回上一级失败, 直接进入首页');
      Taro.reLaunch({
        url:currentEnv.project=='yingjing'?'/pages/index/index':'/pages/movie/index'
      })
    });
  }
}

const Login = () => {
  // 如果登录成功, 就返回上一级
  useDidShow(() => {
    checkIsNeedBack();
  });

  return handleMiniprogram()?<View></View>:process.env.TARO_ENV !== 'h5' ? <WechatWrap /> : <LoginH5 />;
};
export default Login